package offer.easy;

public class LastRemain {

    public static int lastOne(int n,int m) {
        if (n == 0) {
            return -1;
        }
        int out = 0;
        int count = n;
        int index = 0;
        int[] array = new int[n];
        for (int i = 0; i < n; i++) {
            array[i] = i;
        }
        while (count > 1) {
            if (array[index] == -1) {
                index = (index+1)%n;
            } else if (out == m-1) {
                array[index] = -1;
                index = (index+1)%n;
                out = (out+1)%m;
                count--;
            } else {
                out = (out+1)%m;
                index = (index+1)%n;
            }
        }
        for (int i = 0; i < n; i++) {
            if (array[i] != -1) {
                index = i;
                break;
            }
        }
        return array[index];
    }

    public static void main(String[] args) {
        System.out.println(lastOne(5, 1));
    }
}
